/*jslint sloppy: true */
/*global require */
var angular = require('angular');
var LM = require('../global');
var hljs = require('highlight.js/lib/highlight.js');
var RP = require('lemonce-result-parser');
require('./caseview.html');

LM.controller('CaseLog', function ($scope, $sce, $routeParams, $q, $anchorScroll, $location,
								Result, Task, Project, ModalService, PublicResult, PublicTask) {
	var $case, task, caseIndex = $routeParams.caseIndex,
		taskId = $routeParams.taskId,
		isPublic = $routeParams.public,
		projectId = $routeParams.projectId;

	task = $scope.task = (isPublic ? PublicTask : Task).get({ taskId: taskId, projectId: projectId }, function () {
		var codeRaw, result;

		task.schemas = angular.fromJson(task.schemas);
		$case = $scope['case'] = task.schemas.caseList[caseIndex];
		codeRaw = $case.code;
		$scope.code = $sce.trustAsHtml(hljs.highlight('lemoncase', codeRaw, true).value);

		result = (isPublic ? PublicResult : Result).query({ projectId: projectId, task: taskId }, function () {
			var resOpts = {name: 's13', tR: []};
			angular.forEach(result, function (r) {
				resOpts.tR.push({ data: angular.fromJson(r.data) });
			});
			$scope.result = new RP(task, resOpts);
			$scope.cRL = [];
			angular.forEach($scope.result.$resultList, function (r) {
				$scope.cRL.push({ cR: r.$caseResultList[caseIndex], rEnv: r.$env });
			});

			setTimeout(function () {
				$anchorScroll(angular.element(document.querySelector('#' + $location.hash())));
			}, 10);
		});
	});
	$scope.showCode = function (line) {
		ModalService.showModal(line, $case.code);
	};

	// init
	$scope.project = Project.get({ projectId: projectId });
	$scope.queryConfig.clear().setActive();
	$scope.navConfig.setHref('#/project/' + projectId + '/task/' + taskId + '/result').setType('back');
	$scope.loop = 0;
});
